package com.qqtech.qquan.delivery.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.ArithUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.delivery.dao.DeliveryOrderDao;
import com.qqtech.qquan.delivery.enums.DeliveryOrderStatusDictEnum;
import com.qqtech.qquan.delivery.model.DeliveryOrder;
import com.qqtech.qquan.delivery.model.DeliveryOrderVo;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.service.OrderHandleService;
import com.qqtech.qquan.user.dao.UserAddressDao;
import com.qqtech.qquan.user.model.UserAddressVo;

@Service
public class DeliveryOrderServiceImpl extends BaseServiceImpl<DeliveryOrder>
		implements DeliveryOrderService {
	public static final Logger log = LoggerFactory.getLogger(DeliveryOrderServiceImpl.class);
	
	@Resource
	private DeliveryOrderDao deliveryOrderDao;
	
	@Resource
	private UserAddressDao userAddressDao;
	
	@Resource
	private OrderHandleService orderHandleService;

	@Override
	protected BaseDao<DeliveryOrder> getBaseDao() {
		return deliveryOrderDao;
	}
	
	@Override
	public DeliveryOrderVo getByOrderNo(java.lang.String orderNo) {
		return deliveryOrderDao.getByOrderNo(orderNo);
	}

	@Override
	public Result handleSaveOrder(DeliveryOrderVo deliveryOrderVo) {
		Result result = new Result();
		double tyj_x = 113.86996098691093;
		double tyj_y = 22.62039016053022;
		UserAddressVo userAddress = userAddressDao.getById(deliveryOrderVo.getAddressId());
		if (userAddress == null) {
			result.addErr("地址不存在");
			return result;
		}
		if (userAddress.getCommunityId() == null) {
			result.addErr("地址信息不完整，请重新编辑您的地址");
			return result;
		}
		double price = 0;
		double distance = ArithUtil.getDistance(userAddress.getX().doubleValue(), userAddress.getY().doubleValue(),
				tyj_x, tyj_y);
		if (distance < 5000) {
			price = 0;
		} else if (distance < 10000) {
			price = 5;
		} else if (distance < 20000) {
			price = 10;
		} else if (distance < 40000) {
			price = 20;
		} else {
			result.addErr("不在代送范围内");
			return result;
		}
		Timestamp now = TimeUtil.now();
		OrderBase orderBase = new OrderBase();
		orderBase.setTotal(new BigDecimal(price));
		orderBase.setTitle("代收代送");
		orderBase.setImg("");
		orderBase.setOrderType(OrderBaseOrderTypeDictEnum.DELIVERY.getCode());
		orderBase.setBuyerId(deliveryOrderVo.getCreatorId());
		orderBase.setSellerId(0);
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setOrderStatusAt(now);
		orderBase.setPayType(OrderBasePayTypeDictEnum.ONDELIVERY.getCode());
		if (price == 0) {
			orderBase.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode()); //0表示免费，状态为已付款
		} else {
			orderBase.setPayStatus(OrderBasePayStatusDictEnum.UNPAYED.getCode());
		}
		orderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.UNSEND.getCode());
		orderBase.setDeliveryStatusAt(now);
		orderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.NONEED.getCode());
		orderBase.setReturnStatusAt(now);
		orderBase.setIsCallBack(YesNoEnum.NO.getCode());
		orderBase.setAutoExpireAt(TimeUtil.addMins(now, 15)); // 未付款情况下自动失效时间
		orderBase.setCommunityId(userAddress.getCommunityId());
		// 收货地址
		OrderDelivery orderDelivery = new OrderDelivery();
		orderDelivery.setType(OrderDeliveryTypeDictEnum.SELLERSERVICE.getCode());
		orderDelivery.setDeliveryName("");
		orderDelivery.setDeliveryNo("");
		orderDelivery.setConsignee(userAddress.getContactName());
		orderDelivery.setPhone(userAddress.getContactPhone());
		orderDelivery.setAddress(userAddress.getAddress());
		List<OrderItem> listItem = new ArrayList<OrderItem>();
		result = orderHandleService.createOrder(orderBase, orderDelivery, listItem);
		if (result.checkForm()) {
			deliveryOrderVo.setNewAt(now);
			deliveryOrderVo.setOrderNo(result.get("orderNo").toString());
			deliveryOrderVo.setStatus(DeliveryOrderStatusDictEnum.NoStorage.getCode()); //待入库
			deliveryOrderVo.setStatusAt(now);
			deliveryOrderVo.setUpdAt(now);
			deliveryOrderDao.insert(deliveryOrderVo);
		}
		return result;
	}

	@Override
	public Result handleInStorage(Integer id) {
		Result result = new Result();
		DeliveryOrderVo deliveryOrder = null;
		if (id == null) {
			result.addErr("id为空");
		} else {
			deliveryOrder = getById(id);
			if (deliveryOrder == null) {
				result.addErr("数据不存在");
			} else if (deliveryOrder.getStatus() != DeliveryOrderStatusDictEnum.NoStorage.getCode()) {
				result.addErr("只有状态是待入库，才能入库");
			}
		}
		if (result.checkForm()) {
			deliveryOrder.setStatus(DeliveryOrderStatusDictEnum.NoSign.getCode());
			deliveryOrder.setStatusAt(TimeUtil.now());
			deliveryOrder.setUpdAt(deliveryOrder.getStatusAt());
			updateById(deliveryOrder);
			// 同时更新订单状态为已发货
			OrderDelivery orderDelivery = new OrderDelivery();
			orderDelivery.setOrderNo(deliveryOrder.getOrderNo());
			result = orderHandleService.sended(deliveryOrder.getOrderNo(), 2, 1, null, null); //不需要物流
			if (!result.checkForm()) {
				throw new OrderException(result.getMsg());
			}
		}
		return result;
	}	
}